package com.zhiqianbao.activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.zhiqianbao.R;
import com.zhiqianbao.entity.Repay;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.File2Code;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.ValidateUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/3/11.
 */
public class ZfbConfirmActivity extends BaseActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    private static final String TAG = ZfbConfirmActivity.class.getSimpleName();
    /**
     * 支付宝账号
     */
    EditText edittextZfbzhContent;

    /**
     * 支付宝转账金额
     */
    EditText edittextZzjeContent;
    /**
     * 支付宝转账时间
     */
    EditText edittextZzsjContent;
    /**
     * 上传照片
     */
    ImageView imageViewTakeAccessoryPic;
    /**
     * 提交按钮
     */
    Button buttonSubmitAccessoryOK;

    /**
     * 预览图片的地址
     */
    String currentImagePath;
    String currentImagePathTemp;

    /**
     *
     */
    Repay repay;

    ImageLoader imageLoader = ImageLoader.getInstance();


    Handler confirmHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result<String> result = (Result<String>) msg.obj;
                    if(result!=null) {
                        if (result.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            showShortToast1("保存成功");
                            //关闭当前页面
                            ZfbConfirmActivity.this.finish();
                        } else {
                            showShortToast1(result.getMsg());
                        }
                    }
                    break;
            }
            closeWaitDialog();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zfb_confirm);
        init();
        initView();
    }

    private void initView() {
         edittextZfbzhContent=(EditText)findViewById(R.id.edittext_zfbzh_content);
         edittextZzjeContent=(EditText)findViewById(R.id.edittext_zzje_content);
         edittextZzsjContent=(EditText)findViewById(R.id.edittext_zzsj_content);
         imageViewTakeAccessoryPic=(ImageView)findViewById(R.id.imageView_takeAccessory_Pic);
         buttonSubmitAccessoryOK=(Button)findViewById(R.id.button_submitAccessory_OK);
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
        Intent intent = getIntent();
        repay = (Repay) intent.getSerializableExtra("repay");


        edittextZzsjContent.setOnClickListener(this);
        imageViewTakeAccessoryPic.setOnClickListener(this);
        buttonSubmitAccessoryOK.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(R.id.edittext_zzsj_content==v.getId()) {
                Calendar now = Calendar.getInstance();
                DatePickerDialog dpd = DatePickerDialog.newInstance(
                        ZfbConfirmActivity.this,
                        now.get(Calendar.YEAR),
                        now.get(Calendar.MONTH),
                        now.get(Calendar.DAY_OF_MONTH)
                );
                dpd.setAccentColor(Color.parseColor("#ffdb3c22"));
                dpd.show(getFragmentManager(), "Datepickerdialog");
        }
        else if(R.id.imageView_takeAccessory_Pic==v.getId()) {
            //上传照片
                showPhotoDialog();
        }
        else if(R.id.button_submitAccessory_OK==v.getId()){
            //提交
                final String repayId = repay.getId().toString();
                final String account = edittextZfbzhContent.getText().toString();
                final String repayTime = edittextZzsjContent.getText().toString();
                final String repayMoney = edittextZzjeContent.getText().toString();
                //支付宝
                final String type = "1";
                if (StringUtils.isBlank(account)) {
                    showShortToast1("请填入支付宝账号");
                    return;
                }
                if (StringUtils.isBlank(repayMoney)) {
                    showShortToast1("请填入转账金额");
                    return;
                }
                if (StringUtils.isBlank(repayTime)) {
                    showShortToast1("请选择转账时间");
                    return;
                }
                if (!ValidateUtils.isUsername(repayMoney)) {
                    showShortToast1("请填入正确的转账金额");
                    return;
                }
                if (StringUtils.isBlank(currentImagePath)) {
                    showShortToast1("请上传凭证");
                    return;
                }

                Bitmap bitmap = imageLoader.loadImageSync("file://" + currentImagePath);
                if (bitmap == null) {
                    showShortToast1("请重新上传凭证");
                    return;
                }

                final String voucherPic = File2Code.bitmapToBase64(bitmap, 500);
                showWaitDialog();
                //调用提交转账记录接口
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, String> params = new HashMap<>();
                        params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                        params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");

                        params.put("repayId", repayId);
                        params.put("account", account);
                        params.put("repayMoney", repayMoney);
                        params.put("repayTime", repayTime);
                        params.put("type", type);
                        params.put("voucherPic", voucherPic);

                        Message message = new Message();
                        String  result = HttpUtils.httpPostString(Constants.API_ROOT + "/repay/offlineRepay", params, ZfbConfirmActivity.this);
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            message.what = RESULT_OK;
                            Result<String> data = Result.fromJson(result, String.class);
                            message.obj = data;
                        }
                        confirmHandler.sendMessage(message);
                    }
                }).start();

        }
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        monthOfYear += 1;
        edittextZzsjContent.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
    }


    private void showPhotoDialog() {
        final List<String> menus = new ArrayList<>();

        menus.add("拍照上传");
        menus.add("手机相册");
        menus.add("预览大图");
        AlertDialog.Builder builder = new AlertDialog.Builder(ZfbConfirmActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.activity_bank_one, null);
        TextView title = (TextView) view.findViewById(R.id.textview_bank_title);
        title.setText("选择图片位置");
        ListView listView = (ListView) view.findViewById(R.id.listView_bank);
        //修改高度
        final ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = ActionBar.LayoutParams.WRAP_CONTENT;
        listView.setLayoutParams(params);
        listView.setAdapter(new ArrayAdapter<String>(ZfbConfirmActivity.this, android.R.layout.simple_list_item_1, menus));
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        dialog.show();
        //弹出框绑定方法
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (menus.get(position)) {
                    case "拍照上传":
                        getImageFromCamera();
                        break;
                    case "预览大图":
                        Intent bigPicIntent = new Intent(ZfbConfirmActivity.this, BigPicDialogActivity.class);
                        bigPicIntent.putExtra("bitmap", currentImagePath);
                        startActivity(bigPicIntent);
                        break;
                    case "手机相册":
                        getImageFromGallery();
                        break;
                }
                dialog.cancel();
            }
        });
        //关闭弹出框按钮
        TextView button = (TextView) view.findViewById(R.id.bank_dialog_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            currentImagePathTemp = FileUtils.getPhotopath();
            Uri uri = Uri.fromFile(new File(currentImagePathTemp));
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(getImageByCamera, Constants.REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            showShortToast1("请确认已经插入SD卡");
        }
    }

    protected void getImageFromGallery () {
        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 3);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK) {
            return;
        }

        ImageSize targetSize = new ImageSize(160, 100);
        switch (requestCode) {
            case Constants.REQUEST_CODE_CAPTURE_CAMEIA:
                Log.i(this.getClass().toString(), "拍照返回");
                currentImagePath = currentImagePathTemp;
                imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic, targetSize);
                break;
            case 3 :
                Log.i(this.getClass().toString(), "相册返回");
                Uri selectedImage = data.getData();

                String path = selectedImage.getPath();

                Log.i(TAG, path);

                //小米
                if (path.indexOf(".") != -1) {
                    currentImagePath = path;
                } else {
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    currentImagePath = cursor.getString(columnIndex);
                    Log.d(TAG, currentImagePath);
                    cursor.close();
                }
                imageLoader.displayImage("file://" + currentImagePath, imageViewTakeAccessoryPic, targetSize);
                break;
        }
    }
}
